package com.joiant.community.controller;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.joiant.community.dto.AccessTokenDTO;
import com.joiant.community.dto.GiteeUser;
import com.joiant.community.mapper.UserMapper;
import com.joiant.community.model.User;
import com.joiant.community.provider.GiteeProvider;
import com.joiant.community.service.UserService;

@Controller
public class AuthorizeController {
	
	@Autowired
	private GiteeProvider giteeProvider;
	
	@Value("${gitee.client.id}")
	private String clientId;
	
	@Value("${gitee.client.secret}")
	private String clientSecret;
	
	@Value("${gitee.redirect.uri}")
	private String redirectUri;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserService userService;
	
	@GetMapping("/callback")
	public String callback(@RequestParam(name="code")String code
			,HttpServletResponse response) {
		AccessTokenDTO accessTokenDTO = new AccessTokenDTO(); 
		accessTokenDTO.setClient_id(clientId);
		accessTokenDTO.setClient_secret(clientSecret);
		accessTokenDTO.setCode(code);
		accessTokenDTO.setRedirect_uri(redirectUri);
		accessTokenDTO.setGrant_type("authorization_code");
		String accessToken = giteeProvider.getAccessToken(accessTokenDTO);
		GiteeUser giteeUser = giteeProvider.getUser(accessToken);
		if(giteeUser != null && giteeUser.getId() != null) {
			User user = new User();
			String token = UUID.randomUUID().toString();
			user.setToken(token);
			user.setName(giteeUser.getName());
			user.setAccountId(String.valueOf(giteeUser.getId()));
			
			user.setAvatarUrl(giteeUser.getAvatar_url());
			userService.createOrUpdate(user);
			response.addCookie(new Cookie("token", token));
			return "redirect:/";
		}else {
			//登录失败，重新登录
			return "redirect:/";
		}
	}

}
